package com.jdd.modules.projectusertype.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.AutoLog;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.common.util.ResultGenerator;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.entity.params.ImportParams;
import com.jdd.common.util.excel.util.ExcelImportUtil;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.dao.entity.TProject;
import com.jdd.dao.service.TProjectService;
import com.jdd.modules.projectusertype.entity.ProjectUserType;
import com.jdd.modules.projectusertype.service.IProjectUserTypeService;
import com.jdd.modules.userstaff.entity.User;
import com.jdd.modules.userstaff.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 项目人员类型
 * @Author: jdd
 * @Date:   2022-03-23
 * @Version: V1.0
 */
@Slf4j
@Api(tags="项目人员类型")
@RestController
@RequestMapping("/projectUserType/projectUserType")
public class ProjectUserTypeController {
	@Autowired
	private IProjectUserTypeService projectUserTypeService;
	@Autowired
	private TProjectService tProjectService;

	@Resource
	private IUserService userService;



	 @AutoLog(value = "项目")
	 @ApiOperation(value="项目", notes="项目")
	 @GetMapping(value = "/projectInfo")
	 public Result<List<TProject>> selectProject(){
		 List<String> projectCodes = LoginUserUtils.getLoginUser().getProjectCodes();
		 if (projectCodes.size()<=0){
		 	return ResultGenerator.genSuccessResult(new ArrayList<>());
		 }
		 Result<List<TProject>> result = new Result<>();
		 QueryWrapper wrapper = new QueryWrapper();
		 wrapper.groupBy("name");
		 wrapper.in("id",projectCodes);
		 List<TProject> list = tProjectService.list(wrapper);
		 result.setResult(list);
		 return result;
	 }

	/**
	  * 分页列表查询
	 * @param projectUserType
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "项目人员类型-分页列表查询")
	@ApiOperation(value="项目人员类型-分页列表查询", notes="项目人员类型-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ProjectUserType>> queryPageList(ProjectUserType projectUserType,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		Result<IPage<ProjectUserType>> result = new Result<IPage<ProjectUserType>>();
		List<String> projectCodes = LoginUserUtils.getLoginUser().getProjectCodes();
		if (projectCodes.size()<=0){
			return result;
		}
		Page<ProjectUserType> page = new Page<ProjectUserType>(pageNo, pageSize);
		IPage<ProjectUserType> pageList = projectUserTypeService.findList(page,projectCodes);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  *   查询项目下的人员类型集合
	  * @param projectId
	  * @return
	  */
	 @AutoLog(value = "查询项目下的人员类型集合-查询")
	 @ApiOperation(value="查询项目下的人员类型集合-查询", notes="查询项目下的人员类型集合-查询")
	 @PostMapping(value = "/getUserTypeListByProjectId")
	 public Result<List<ProjectUserType>> getUserTypeListByProjectId(@RequestBody String projectId) {
		 Result<List<ProjectUserType>> result = new Result<>();
		 LambdaQueryWrapper<ProjectUserType> wrapper = new LambdaQueryWrapper<>();
		 wrapper.eq(ProjectUserType::getProjectId,projectId);
		 List<ProjectUserType> list = projectUserTypeService.list(wrapper);
		 result.setSuccess(true);
		 result.setMessage("查询成功");
		 result.setResult(list);
		 return result;
	 }

	/**
	  *   添加
	 * @param projectUserType
	 * @return
	 */
	@AutoLog(value = "项目人员类型-添加")
	@ApiOperation(value="项目人员类型-添加", notes="项目人员类型-添加")
	@PostMapping(value = "/add")
	public Result<ProjectUserType> add(@RequestBody ProjectUserType projectUserType) {
		Result<ProjectUserType> result = new Result<ProjectUserType>();
		/*查询是否有重名的类型*/
		LambdaQueryWrapper<ProjectUserType> projectUserTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
		projectUserTypeLambdaQueryWrapper.eq(ProjectUserType::getProjectId,projectUserType.getProjectId());
		projectUserTypeLambdaQueryWrapper.eq(ProjectUserType::getTypeName,projectUserType.getTypeName());
		int count = projectUserTypeService.count(projectUserTypeLambdaQueryWrapper);
		if (count>0){
			result.error500("添加失败，项目下存在重名类型");
			return result;
		}
		TProject tProject = tProjectService.getById(projectUserType.getProjectId());
		projectUserType.setProjectName(tProject.getName());
		try {
			projectUserTypeService.save(projectUserType);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	  *  编辑
	 * @param projectUserType
	 * @return
	 */
	@AutoLog(value = "项目人员类型-编辑")
	@ApiOperation(value="项目人员类型-编辑", notes="项目人员类型-编辑")
	@PutMapping(value = "/edit")
	public Result<ProjectUserType> edit(@RequestBody ProjectUserType projectUserType) {
		log.info("编辑:"+projectUserType);
		Result<ProjectUserType> result = new Result<ProjectUserType>();

		ProjectUserType projectUserTypeEntity = projectUserTypeService.getById(projectUserType.getId());
		if(projectUserTypeEntity==null) {
			result.error500("未找到对应实体");
		}else {
			/*查询是否有重名的类型*/
			LambdaQueryWrapper<ProjectUserType> projectUserTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
			projectUserTypeLambdaQueryWrapper.eq(ProjectUserType::getProjectId,projectUserType.getProjectId());
			projectUserTypeLambdaQueryWrapper.eq(ProjectUserType::getTypeName,projectUserType.getTypeName());
			projectUserTypeLambdaQueryWrapper.ne(ProjectUserType::getTypeName,projectUserTypeEntity.getTypeName());
			int count = projectUserTypeService.count(projectUserTypeLambdaQueryWrapper);
			if (count>0){
				result.error500("添加失败，项目下存在重名类型");
				return result;
			}
			boolean ok = projectUserTypeService.updateById(projectUserType);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目人员类型-通过id删除")
	@ApiOperation(value="项目人员类型-通过id删除", notes="项目人员类型-通过id删除")
	@PostMapping(value = "/delete")
	public Result<?> delete(@RequestBody JSONObject idJSON) {
		int id = Integer.parseInt(idJSON.getString("ids"));
		try {
			projectUserTypeService.removeById(id);
			LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
			userLambdaQueryWrapper.eq(User::getProjectUserTypeId,id);
			int userNum = userService.count(userLambdaQueryWrapper);
			if (userNum>0){
				return Result.error("删除失败,该类型下存在人员");
			}
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}


	 /**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目人员类型-批量删除")
	@ApiOperation(value="项目人员类型-批量删除", notes="项目人员类型-批量删除")
	@PostMapping(value = "/deleteBatch")
	public Result<ProjectUserType> deleteBatch(@RequestBody JSONObject idListJSON) {
		Result<ProjectUserType> result = new Result<ProjectUserType>();
		String ids = idListJSON.getString("ids");
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			List<String> idList = Arrays.asList(ids.split(","));
			LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
			userLambdaQueryWrapper.in(User::getProjectUserTypeId,idList);
			int userNum = userService.count(userLambdaQueryWrapper);
			if (userNum>0){
				result.error500("部分类型下存在用户！");
				return result;
			}
			this.projectUserTypeService.removeByIds(idList);
			result.success("批量删除成功!");
		}
		return result;
	}






	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目人员类型-通过id查询")
	@ApiOperation(value="项目人员类型-通过id查询", notes="项目人员类型-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ProjectUserType> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ProjectUserType> result = new Result<ProjectUserType>();
		ProjectUserType projectUserType = projectUserTypeService.getById(id);
		if(projectUserType==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(projectUserType);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response,ProjectUserType projectUserType) {
      // Step.1 组装查询条件
       QueryWrapper<ProjectUserType> queryWrapper = QueryGenerator.initQueryWrapper(projectUserType, request.getParameterMap());

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
      List<ProjectUserType> pageList = projectUserTypeService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "项目人员类型列表");
      mv.addObject(NormalExcelConstants.CLASS, ProjectUserType.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目人员类型列表数据", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = ImportParams.builder().build();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ProjectUserType> listProjectUserTypes = ExcelImportUtil.importExcel(file.getInputStream(), ProjectUserType.class, params);
              projectUserTypeService.saveBatch(listProjectUserTypes);
              return Result.ok("文件导入成功！数据行数:" + listProjectUserTypes.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
